package com.czhoujunlv.drug;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.czhoujunlv.drug.Bean.LoginData;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class MainActivity extends AppCompatActivity {

    EditText id, password,code;
    TextView forget, verification, register;
    ConstraintLayout Login;
    String json, idName, psWord,Code;
    ImageView codeImg;
    LoginData loginData= new LoginData();
    public static String token;
    public static int idCode;

    public final static int CONNECT_TIMEOUT = 60;
    public final static int READ_TIMEOUT = 100;
    public final static int WRITE_TIMEOUT = 60;
    public static final OkHttpClient client = new OkHttpClient.Builder()
            .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)//设置读取超时时间
            .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)//设置写的超时时间
            .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)//设置连接超时时间
            .build();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化控件
        initButton();
        //获取验证码
        Glide.with(MainActivity.this)
                .load("http://192.168.43.138:8080/index/code?num=1")
                .skipMemoryCache(true)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .into(codeImg);
        //刷新验证码
        codeImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Glide.with(MainActivity.this)
                        .load("http://192.168.43.138:8080/index/code?num=1")
                        .skipMemoryCache(true)//清除缓存，实现刷新
                        .diskCacheStrategy(DiskCacheStrategy.NONE)//取消磁盘缓存
                        .into(codeImg);
            }
        });

        //登录验证
        Login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                idName = id.getText().toString();
                psWord = password.getText().toString();// "account": "string",
                Code = code.getText().toString();
                json = "{" + "\"" + "account" + "\"" + ": " + "\"" + idName + "\"" +
                        "," + "\"" + "pass" + "\"" + ": " + "\"" + psWord + "\"" +
                        "," + "\"" + "code" + "\"" + ": " + "\"" + Code + "\"" +
                        "," + "\"" + "codeId"+ "\""+ ":"  + "\"" + "1" +"\"" + "}";
                Log.i("Json字符串", json);

                final MyApplication application = (MyApplication)MainActivity.this.getApplication();

                Thread thread = new Thread() {
                    @Override
                    public void run() {
                        super.run();
                        try {
                            String res = post("http://192.168.43.138:8080/index/consumer/login", json);//登录接口
                            Gson gson = new Gson();
                            loginData = gson.fromJson(res, LoginData.class);
                            if (loginData.getCode() == 200) {
                                token = loginData.getData().getToken();
                                idCode = loginData.getData().getId();
                                SharedPreferences sharedPreferences = getSharedPreferences("user", MODE_PRIVATE);//拿到 sharedPreferences 的引用 MODE_PRIVATE表示只能被本应用读写，不能被其他应用读写
                                SharedPreferences.Editor editor = sharedPreferences.edit();//拿到编辑对象
                                editor.putBoolean("isLogin", true);//添加数据
                                editor.putString("token",token);
                                editor.commit();
                                //EventBus.getDefault().register(this);
                                EventBus.getDefault().post(loginData.getData().getName());
                                finish();//关掉登录页
                            }else{
                                Toast.makeText(MainActivity.this,"验证码错误",Toast.LENGTH_SHORT).show();
                            }
                            Log.i("login解析后的数据：", token);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                };
                thread.start();
            }
        });
        //忘记密码
        forget.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this,"联系管理员重置密码",Toast.LENGTH_SHORT).show();
            }
        });
        //注册
        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,Register.class);
                startActivity(intent);
            }
        });
        //短信验证登录
        verification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this,"程序员小波正在加班开发中",Toast.LENGTH_SHORT).show();
            }
        });
    }
    //验证登录状态
    public static String post(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            String res = response.body().string();
            Log.i("返回结果：", res);
            return res;
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }
    //获取验证码
    public static String get(String url) throws IOException{
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Response response = client.newCall(request).execute();
        if(response.isSuccessful()){
            String res = response.body().string();
            Log.i("得到图片：",res);
            return res;
        }else{
            throw new IOException("Unexpected code " + response);
        }
    }
    /**
     * 字符串转Bitmap
     * @param string
     * @return
     */
    public static Bitmap stringtoBitmap(String string) {
        // 字符串转Bitmap
        Bitmap bitmap = null;
        try{
            byte[] bitmapArray;
            bitmapArray = Base64.decode(string, Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0,
                    bitmapArray.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }
    private void initButton(){
        id = findViewById(R.id.id);
        password = findViewById(R.id.password);
        code = findViewById(R.id.verificationCode);
        codeImg = findViewById(R.id.codeImg);
        forget = findViewById(R.id.forget_password);
        verification = findViewById(R.id.verification);
        register = findViewById(R.id.register);
        Login = findViewById(R.id.login);
    }
}